package com.drinks.yiniang.ui.activity.community;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.community.CommunityCommentsAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.comment.CommentJson;
import com.drinks.yiniang.entity.comment.CommentSubmitJson;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.KeyBoardUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.ui.widget.textview.BorderTextView;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 社区动态的评论
 *
 * @author han
 * @date 2019/09/10
 */
public class CommunityActCommentsActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        TextView.OnEditorActionListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    private final String TYPE_API_DO_COLLECT = "1";
    private final String TYPE_API_DO_LIKE = "0";

    //nav
    private NavigationBarLayout nav_bar_community_comments;
    private BaseRecyclerView rcv_community_comments;
    //头像
    private CircleImageView iv_community_comments_avatar;
    //输入框
    private EditText et_community_comments_input;
    //header view
    //酒单名称
    private BorderTextView tv_cc_wine_list_name;
    //赞同数
    private TextView tv_cc_like_num;
    //心愿数
    private TextView tv_cc_wish_num;

    private CommunityCommentsAdapter mCommentAdapter;

    //社区活动id
    private String mActId;
    //回复的当前评论id
    private String mPid;
    //是否收藏酒单,1-是
    private String mCollectStatus;
    //是否点赞酒单,1-是
    private String mLiekStatus;

    private int mPages;

    @Override
    protected void initView() {
        nav_bar_community_comments = findViewById(R.id.nav_bar_community_comments);

        rcv_community_comments = findViewById(R.id.rcv_community_comments);

        iv_community_comments_avatar = findViewById(R.id.iv_community_comments_avatar);

        et_community_comments_input = findViewById(R.id.et_community_comments_input);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        getWindow().getDecorView().setBackgroundColor(Color.WHITE);

        mContext = this;

        mActId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyCommunityId) : null;

        KeyBoardUtils.assistActivity(this);
        initAdapter();
        getCommentsList();
    }

    private void initAdapter() {
        rcv_community_comments.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_community_comments.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mCommentAdapter = new CommunityCommentsAdapter(mContext, new ArrayList<CommentJson.CommentList>());
        mCommentAdapter.addHeaderView(getHeaderView());
        mCommentAdapter.setHeaderAndEmpty(true);
        mCommentAdapter.setCommonEmpty(getLayoutInflater(), rcv_community_comments);
        mCommentAdapter.bindToRecyclerView(rcv_community_comments);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_community_comments, (ViewGroup) rcv_community_comments.getParent(), false);

        tv_cc_wine_list_name = mHeaderView.findViewById(R.id.tv_cc_wine_list_name);

        tv_cc_like_num = mHeaderView.findViewById(R.id.tv_cc_like_num);
        tv_cc_wish_num = mHeaderView.findViewById(R.id.tv_cc_wish_num);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_community_comments.setOnNavgationBarClickListener(this);
        tv_cc_like_num.setOnClickListener(this);
        tv_cc_wish_num.setOnClickListener(this);
        et_community_comments_input.setOnEditorActionListener(this);
        mCommentAdapter.setOnItemClickListener(this);
        mCommentAdapter.setOnLoadMoreListener(this, rcv_community_comments);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cc_like_num://点赞
                doCollectOrLike(TYPE_API_DO_LIKE);
                break;
            case R.id.tv_cc_wish_num://收藏
                doCollectOrLike(TYPE_API_DO_COLLECT);
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_community_comments;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        //refresh
        getCommentsList();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            hideKeyboard(this.getCurrentFocus().getWindowToken());
            //TODO Search
            doComment(StringUtils.getEditTextString(et_community_comments_input.getText()));
        }

        return false;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        CommentJson.CommentList data = mCommentAdapter.getItem(position);

        if (data == null) {
            return;
        }

        mPid = data.getId();
        et_community_comments_input.setHint("回复" + StringUtils.getNoNullString(data.getNickname()));
        et_community_comments_input.setFocusable(true);   //设置可以获取焦点
        et_community_comments_input.setFocusableInTouchMode(true);
        et_community_comments_input.requestFocus();
        showKeyboard(et_community_comments_input);
    }

    //评价
    private void doComment(String content) {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        if (StringUtils.isEmpty(mActId)) {
            ToastUtils.showShort(R.string.text_act_not_exist);
            return;
        }

        if (StringUtils.isEmpty(content)) {
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityActComments(mActId, content, mPid,
                new APIRequestCallback<CommentSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CommentSubmitJson res) {
                        mPid = null;
                        et_community_comments_input.setText("");
                        et_community_comments_input.setHint(R.string.text_add_comments_dot);
                        getCommentsList();
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //收藏
    private void doCollectOrLike(final String type) {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        if (StringUtils.isEmpty(mActId)) {
            ToastUtils.showShort(R.string.text_act_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityActCollectOrLike(type, mActId, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if (TYPE_API_DO_LIKE.equals(type)) {
                    mLiekStatus = Constants.STATUS_GLOBAL_YES.equals(mLiekStatus) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES;
                    setLikeStatus(res.getData());
                } else {
                    mCollectStatus = Constants.STATUS_GLOBAL_YES.equals(mCollectStatus) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES;
                    setCollectStatus(res.getData());
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        CommunityApiIO.getInstance().getCommunityActCommentsList(mActId, mPages, new APIRequestCallback<CommentJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommentJson res) {
                if (mCommentAdapter == null) {
                    return;
                }

                mPages++;

                if (res.getData().getData() == null) {
                    res.getData().setData(new ArrayList<CommentJson.CommentList>());
                }

                mCommentAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mCommentAdapter.loadMoreComplete();
                } else {
                    mCommentAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mCommentAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    //获取评论列表
    private void getCommentsList() {
        if (StringUtils.isEmpty(mActId)) {
            ToastUtils.showShort(R.string.text_act_not_exist);
            return;
        }

        showLoadingDialog();

        mPages = 1;

        CommunityApiIO.getInstance().getCommunityActCommentsList(mActId, mPages, new APIRequestCallback<CommentJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommentJson res) {
                if (mCommentAdapter == null) {
                    return;
                }

                setCommunityData(res.getData().getActivities());

                mPages++;

                if (res.getData().getData() == null) {
                    res.getData().setData(new ArrayList<CommentJson.CommentList>());
                }

                mCommentAdapter.getData().clear();
                mCommentAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mCommentAdapter.loadMoreComplete();
                } else {
                    mCommentAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mCommentAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setCommunityData(CommentJson.CommentInfo data) {
        if (data == null) {
            return;
        }

        mCollectStatus = data.getIs_collect();
        mLiekStatus = data.getIs_like();

        tv_cc_wine_list_name.setText(data.getTitle());
        setCollectStatus(data.getCollect_count());
        setLikeStatus(data.getLike_count());
    }

    private void setCollectStatus(String num) {
        tv_cc_wish_num.setText(StringUtils.getNullEmptyConvertZero(num));

        if (Constants.STATUS_GLOBAL_YES.equals(mCollectStatus)) {//已收藏
            tv_cc_wish_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_wishlist_p, 0, 0, 0);
        } else {
            tv_cc_wish_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_wishlist_n, 0, 0, 0);
        }
    }

    private void setLikeStatus(String num) {
        tv_cc_like_num.setText(StringUtils.getNullEmptyConvertZero(num));

        if (Constants.STATUS_GLOBAL_YES.equals(mLiekStatus)) {//已点赞
            tv_cc_like_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_like_p, 0, 0, 0);
        } else {
            tv_cc_like_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_like_n, 0, 0, 0);
        }
    }
}
